package com.zj.osm.view.map.offline

import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import android.location.Location
import android.os.Build
import android.os.Bundle
import android.preference.PreferenceManager
import android.util.Log
import android.view.View
import androidx.annotation.RequiresApi
import com.example.location_library.china_location.ChinaLocation
import com.example.location_library.china_location.ChinaLocationNotifyChange
import com.example.location_library.china_location.ChineLocationBean
import com.example.location_library.china_location.LocationType
import com.zj.osm.R
import com.zj.osm.view.BaseActivity
import com.zj.utils.map.GoogleTileSource
import com.zj.utils.utils.utilcode.ToastUtils
import kotlinx.android.synthetic.main.activity_down_offline_map.*
import org.osmdroid.api.IGeoPoint
import org.osmdroid.api.IMapController
import org.osmdroid.config.Configuration
import org.osmdroid.util.GeoPoint
import org.osmdroid.views.overlay.Marker
import org.osmdroid.views.overlay.Polygon
import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider
import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay
import java.io.Serializable
import java.util.*


class DownOfflineMapActivity : BaseActivity(), View.OnClickListener, ChinaLocationNotifyChange {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val ctx = applicationContext
        Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx))
        setContentView(R.layout.activity_down_offline_map)
        ChinaLocation.getInstance().setContext(this).setLocationType(LocationType.GAO_DE).initLocation()
        initView()
        initMap()
    }

    private fun initView() {
        downOffTitleBar.setTitle("离线地图")
        downOffTitleBar.setBackImageVisiable(true)
        downOffTitleBar.setRightText("下一步")
        downOffTitleBar.setRightTextOnClickListener {
            downMap()
        }
        downOffBlodUp.setOnClickListener(this)
        downOffBlodDown.setOnClickListener(this)
        downOffBtnTower.setOnClickListener(this)
        downOffUndo.setOnClickListener(this)
        downOffReset.setOnClickListener(this)
    }

    private var isfirst: Boolean=true
    private lateinit var mapController: IMapController
    private lateinit var mLocationOverlay: MyLocationNewOverlay
    private val geoPoints: MutableList<GeoPoint> = ArrayList()
    private val latList: MutableList<Double> = LinkedList()
    private val longList: MutableList<Double> = LinkedList()
    private val pointsList: MutableList<Marker> = LinkedList()

    private fun initMap() {
        downOffMap.setTileSource(Objects.requireNonNull(GoogleTileSource.GoogleHybrid))
        mapController = downOffMap.controller
        mapController.setZoom(18.0)
        mLocationOverlay = MyLocationNewOverlay(GpsMyLocationProvider(this), downOffMap)
        mLocationOverlay.enableMyLocation()
        downOffMap.setMultiTouchControls(true)
        downOffMap.setBuiltInZoomControls(false)
        downOffMap.maxZoomLevel = 20.0


    }

    private fun downMap() {
        if (geoPoints.size > 2) {
            val north: Double = Collections.max(latList)
            val south: Double = Collections.min(latList)
            val east: Double = Collections.max(longList)
            val west: Double = Collections.min(longList)
            val intent = Intent(this, DownOfflineMapConfigActivity::class.java).apply {
                putExtra("north", north)
                putExtra("south", south)
                putExtra("east", east)
                putExtra("west", west)
            }
            startActivity(intent)
            finish()
        } else {
            ToastUtils.showShort("至少选择三个点")
            return
        }

    }

    override fun onResume() {
        super.onResume()
        if (downOffMap != null) {
            downOffMap.onResume()
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.downOffBlodUp -> {
                mapController.setZoom(downOffMap.zoomLevelDouble + 1)
            }
            R.id.downOffBlodDown -> {
                mapController.setZoom(downOffMap.zoomLevelDouble - 1)
            }
            R.id.downOffBtnTower -> {
                addPoint()
            }
            R.id.downOffUndo -> {
                undoDown()
            }
            R.id.downOffReset -> {
                resetDown()
            }
        }
    }

    /**
     * 撤销
     */
    private fun undoDown() {
        if (geoPoints.size > 0) {
            downOffMap.overlays.remove(pointsList[pointsList.size - 1])
            pointsList.removeAt(pointsList.size - 1)
            geoPoints.removeAt(geoPoints.size - 1)
            latList.removeAt(latList.size - 1)
            longList.removeAt(longList.size - 1)
            drawPolygon()
        }
    }


    /**
     * 重置
     */
    private fun resetDown() {
        // 小于三个点不做操作
        if (geoPoints.size < 3) return
        AlertDialog.Builder(this).setTitle("提示")
                .setMessage("重置后将清除地图上已绘制的多边形，确认要重置吗？")
                .setPositiveButton("确定") { dialog: DialogInterface?, _: Int ->
                    dialog?.dismiss()
                    downOffMap.overlays.removeAll(pointsList)
                    if (polygon != null) {
                        //删除已经绘制的多边形
                        downOffMap.overlays.remove(polygon)
                    }
                    pointsList.clear()
                    geoPoints.clear()
                    latList.clear()
                    longList.clear()
                    downOffMap.invalidate()
                }.setNegativeButton("取消") { dialog: DialogInterface?, _: Int ->
                    dialog?.dismiss()
                }.show()
    }

    private var polygon: Polygon? = null

    private fun addPoint() {
        val mapCenter: IGeoPoint = downOffMap.mapCenter
        latList.add(mapCenter.latitude)
        longList.add(mapCenter.longitude)
        val geoPoint = GeoPoint(mapCenter.latitude, mapCenter.longitude)
        geoPoints.add(geoPoint)
        val marker = Marker(downOffMap)
        marker.icon = resources.getDrawable(R.drawable.ic_offline_point)
        marker.position = geoPoint
        marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
        downOffMap.overlays.add(marker)
        downOffMap.invalidate()
        pointsList.add(marker)
        drawPolygon()
    }

    private fun drawPolygon() {
        if (polygon != null) {
            //删除已经绘制的多边形
            downOffMap.overlays.remove(polygon)
        }

        polygon = Polygon()
        val geoPointList: MutableList<GeoPoint> = ArrayList()
        if (geoPoints.size > 0)
            geoPointList.add(geoPoints[0]) //forces the loop to close(connect last point to first point)

        polygon?.fillPaint?.color = Color.parseColor("#1EFFE70E") //set fill color
        polygon?.strokeWidth = 5f
        polygon?.points = geoPointList

        val holes: MutableList<List<GeoPoint>> = ArrayList()
        holes.add(geoPoints)
        polygon?.holes = holes

        downOffMap.overlayManager.add(polygon)
        downOffMap.invalidate()
    }

    override fun onPause() {
        super.onPause()
        if (downOffMap != null) {
            downOffMap.onPause()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (downOffMap != null) {
            downOffMap.onDetach()
        }
        ChinaLocation.getInstance().close()
    }
    private lateinit var useLocation: Location
    override fun onReceiveLocation(chinaLocationBean: ChineLocationBean) {
        useLocation=Location("")
        useLocation.latitude = chinaLocationBean.chinaLatitude
        useLocation.longitude = chinaLocationBean.chinaLongitude
        if(useLocation.latitude>0&&useLocation.longitude>0&&isfirst){
            val geoPoint = GeoPoint(useLocation.latitude, useLocation.longitude)
            //动画平移到当前位置
            mapController.animateTo(geoPoint, downOffMap.zoomLevelDouble, 100L)
            isfirst=false
        }
    }

}
